package erp_services

import (
	"errors"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/global"
)

type materialService struct {
}

var MaterialService = new(materialService)

func (materialService *materialService) GetMaterialByUnioNo(unionNo string) (material erp_models.Material, err error) {
	err = global.App.DB.Where("union_no = ? ", unionNo).Find(&material).Error

	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 新增原材料
func (materialService *materialService) Create(material erp_models.Material) (uint, error) {
	result := global.App.DB.Create(&material)
	if result.Error != nil {
		return 0, result.Error
	}
	return material.ID.ID, nil
}

func (materialService *materialService) Update(material erp_models.Material) (err error) {
	if err := global.App.DB.Model(&erp_models.Material{}).Where("ID = ?", material.ID.ID).Omit("ID", "UnionNo").Updates(&material).Error; err != nil {
		return err
	}
	return nil
}

// 查询中联原料信息
func (materialService *materialService) GetZlStuffInfos() (zlStuffInfos []erp_models.Material, err error) {

	err = global.App.DB.Where("Status = ? ", 1).Find(&zlStuffInfos).Error

	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 查询原材料信息
func (materialService *materialService) GetZlStuffInfoBySiId(si_id int) (zlSilo erp_models.Material, err error) {

	err = global.App.DB.First(&zlSilo, si_id).Error

	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 根据原料编号查询原材料信息
func (materialService *materialService) GetByMaterialNo(material_no string) (material erp_models.Material, err error) {
	err = global.App.DB.Where("material_no = ?", material_no).First(&material).Error
	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}
